package com.itheima.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.itheima.common.utils.UtilFuns;
import com.itheima.domain.system.Dept;
import com.itheima.service.system.IDeptService;
import com.itheima.web.controller.BaseController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {

    @Autowired
    private IDeptService deptService;


    @RequestMapping(value = "/list",name = "分页查询当前用户所有部门")
    public String list(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size) {

        PageInfo pageInfo = deptService.findAll(super.getCurrentUserCompanyId(), page, size);

        super.request.setAttribute("page", pageInfo);

        return "system/dept/dept-list";
    }

    @RequestMapping(value = "/toAdd",name = "去到添加部门页面")
    public String toAdd() {

        List<Dept> deptList = deptService.findAll(super.getCurrentUserCompanyId());

        request.setAttribute("deptList", deptList);

        return "/system/dept/dept-add";
    }

    @RequestMapping(value = "/edit",name = "保存或者更新部门")
    public String edit(Dept dept) {
        //判断保存还是更新
        if (UtilFuns.isEmpty(dept.getId())) {
            //保存
            //设置不能填写的内容
            dept.setCompanyId(super.getCurrentUserCompanyId());
            dept.setCompanyName(super.getCurrenUserCompanyName());

            deptService.save(dept);
        } else {

            //冲数据库中获取数据
            Dept byId = deptService.findById(dept.getId());

            //如果有数据就替换数据库数据，如果没有就使用从数据库获取的数据
            //替换掉不想替换的数据，companyId，companyName
            //BeanUtils.copyProperties(dept, byId, new String[]{"companyId", "companyName"});

            //更新
            deptService.update(byId);
        }
        return "redirect:/system/dept/list.do";
    }

    @RequestMapping(value = "/toUpdate",name = "去到更新部门页面")
    public String toUpdate(String id) {
        //根据id查询部门  回显数据
        Dept dept = deptService.findById(id);
        request.setAttribute("dept", dept);
        //根据企业id查询所有部门
        List<Dept> deptList = deptService.findAll(super.getCurrentUserCompanyId());
        request.setAttribute("deptList", deptList);
        //前往编辑页面
        return "/system/dept/dept-update";
    }

    @RequestMapping(value = "/delete",name = "删除部门")
    public String delete(String id) {
        deptService.delete(id);
        return "redirect:/system/dept/list.do";
    }
}
